package com.hcy;

import com.jch.Dao.UserDao;
import com.entity.User;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import java.awt.*;
import java.awt.event.*;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;

public class toUpdateFrame extends JDialog {

    private JLabel jl_title;//标题

    private JPanel jp_north;//上部
    private JPanel jp_center;//中部
    private JPanel jp_south;//下部


    private JPanel jp_west;//左边
    private JPanel jp_east;//右边

    private JLabel jl_name;//用户名标签
    private JTextField jtf_name;//用户名文本域
    private JLabel jl_null;
    private JTextArea jta_name;

    private JLabel jl_password;//密码标签
    private JTextField jtf_password;//密码文本域
    private JLabel jl_null2;
    private JTextArea jta_password;//密码提示框

    private JLabel jl_balance;//余额
    private JTextField jtf_balance;
    private JLabel jl_null4;
    private JTextArea jta_balance;//余额提示框

    private JLabel jl_type;
    private JPanel jp_type;
    private JRadioButton jrb_type_man;
    private JRadioButton jrb_type_woman;

    private ButtonGroup buttonGroupSex;


    private JLabel jl_phone;//手机号
    private JTextField jtf_phone;

    private JLabel jl_null3;
    private JTextArea jta_phone;//手机号提示框


    private toUpdateFrame toUpdateFrame;

    private JButton jbt_submit;//提交

    private MainFrame mainFrame;

    private int id;

    private int i;

    private boolean variable = true;
    private boolean isVariable = true;
    private boolean passVariable = true;
    public toUpdateFrame(Frame owner, String title, boolean modal) {
        super(owner, title, modal);
        this.mainFrame = (MainFrame) owner;
        this.getContentPane().setBackground(Color.WHITE);
        setLayout(new BorderLayout());


        createContent();

        jp_north =  new JPanel();
        jl_title = new JLabel(title);
        jp_north.setBackground(Color.WHITE);
        setLabel(jl_title);
        jp_north.add(jl_title);
        add(jp_north, BorderLayout.NORTH);

        jp_center =  new JPanel();
        jp_center.setLayout(new BorderLayout());

        add(jp_center, BorderLayout.CENTER);

        jp_south =  new JPanel();
        jp_south.add(jbt_submit);
        jp_south.setBackground(Color.WHITE);
        add(jp_south, BorderLayout.SOUTH);


        jp_west = new JPanel();
        jp_west.setLayout(new GridLayout(9, 1, 5, 5));
        jp_west.setPreferredSize(new Dimension(80, 0));
        jp_west.setBackground(Color.WHITE);
        jp_center.add(jp_west, BorderLayout.WEST);
        jp_west.add(jl_name);
        jp_west.add(jl_null);
        jp_west.add(jl_password);
        jp_west.add(jl_null2);
        jp_west.add(jl_balance);
        jp_west.add(jl_null4);
        jp_west.add(jl_type);
        jp_west.add(jl_phone);
        jp_west.add(jl_null3);

        jp_east = new JPanel();
        jp_east.setLayout(new GridLayout(9, 1, 5, 5));
        jp_east.setBackground(Color.WHITE);
        jp_center.add(jp_east, BorderLayout.CENTER);

        jp_east.add(jtf_name);
        jp_east.add(jta_name);
        jp_east.add(jtf_password);
        jp_east.add(jta_password);
        jp_east.add(jtf_balance);
        jp_east.add(jta_balance);
        jp_east.add(jp_type);
        jp_east.add(jtf_phone);
        jp_east.add(jta_phone);

        if (this.mainFrame.getPnUser() != null) {
            User user = this.mainFrame.getPnUser();
            id = user.getUid();
            jtf_name.setText(user.getuName());
            jtf_password.setText(user.getuPass());
            jtf_balance.setText(user.getBalance()+"");
            if (user.getuType() == 0) {
                jrb_type_man.setSelected(true);
            } else {
                jrb_type_woman.setSelected(true);
            }
            jtf_phone.setText(user.getUphone());
        }

        //1.先把窗口显示出来
        //标题
        setTitle("增删改查");
        //尺寸
        setSize(500,500);
        //居中
        setLocationRelativeTo(null);
        //设置关闭模式。直接结束整个程序
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        //设置可见
        setVisible(true);

    }

    public void createContent() {


        jl_name = new JLabel("用户名:");
        setLabel(jl_name);
        jtf_name = new JTextField();


        jl_null = new JLabel("");
        setLabel(jl_null);
        jta_name = new JTextArea();
        jtf_name.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {

                jta_name.setFont(new Font("微软雅黑",Font.PLAIN,14));
                jta_name.setText("\n"+"3-16个字符，可使用字母、数字、下划线,中文。");
            }
        });
        jtf_name.addFocusListener(new FocusListener() {

            @Override
            public void focusLost(FocusEvent e) {

                    boolean	email = Pattern.matches("^[\\u4E00-\\u9FA5A-Za-z0-9_]{3,16}$",jtf_name.getText() );

                    if(email==false) {

                        if("".equals(jtf_name.getText()) ) {
                            variable = false;
                            jta_name.setEnabled(false);

                        }
                        else {
                            jta_name.setEnabled(true);
                            jta_name.setFont(new Font("微软雅黑", Font.PLAIN, 14));
                            jta_name.setText("\n"+ "  格式不正确！");
                            variable = false;
                        }

                    }else if(email==true){
                        User user = new User();
                        UserDao userDao = new UserDao();
                        //调用方法查询数据库中是否与昵称文本域中内容相同
                        List<User> users = userDao.queryUsersByuName(jtf_name.getText());
                        for (User user1 : users) {
                            user.setuName(user1.getuName());
                        }

                        jta_name.setEnabled(true);
                        jta_name.setFont(new Font("微软雅黑",Font.PLAIN,14));
                        jta_name.setText("\n"+"  恭喜，该用户名可以使用");
                        variable = true;

                    }





            }
            @Override
            public void focusGained(FocusEvent e) {
                User user = new User();
                UserDao userDao = new UserDao();
                //调用方法查询数据库中是否与昵称文本域中内容相同
                List<User> users = userDao.queryUsersByuName(jtf_name.getText());
                if (jtf_name.getText().equals(user.getuName())){
                    jta_name.setFont(new Font("微软雅黑",Font.PLAIN,14));
                    jta_name.setText("该用户名已被注册，请重新输入");
                    variable = false;
                }
                jta_name.setText("\n"+"3-16个字符，可使用字母、数字、下划线,中文。");

            }
        });

        jl_password = new JLabel("密码:");
        setLabel(jl_password);
        jtf_password = new JTextField();

        jl_null2 = new JLabel("");
        setLabel(jl_null2);
        jta_password = new JTextArea();
        jtf_password.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                jta_password.setFont(new Font("微软雅黑",Font.PLAIN,14));
                jta_password.setText("\n"+"6-16个字符，区分大小写");
            }
        });
        jtf_password.addFocusListener(new FocusListener() {
            @Override
            public void focusLost(FocusEvent e) {
                boolean psw=Pattern.matches("^[A-za-z0-9]{6,16}$",jtf_password.getText());
                if(psw==false) {
                    if("".equals(jtf_password.getText()) ) {
                        passVariable = false;
                        jta_password.setEnabled(false);
                    }else {
                        jta_password.setEnabled(true);
                        jta_password.setFont(new Font("微软雅黑", Font.PLAIN, 14));
                        jta_password.setText("\n" + "  密码错格式错误！");
                        passVariable = false;
                    }
                }else if(psw==true){
                    jta_password.setEnabled(true);
                    jta_password.setFont(new Font("微软雅黑",Font.PLAIN,14));
                    jta_password.setText("\n"+"  恭喜，密码可以使用");
                    passVariable = true;
                }
            }
            @Override
            public void focusGained(FocusEvent e) {

                jta_password.setText("\n"+"6-16个字符，区分大小写");
            }


        });


        jl_balance = new JLabel("余额:");
        setLabel(jl_balance);
        jtf_balance = new JTextField();
        jl_null4 = new JLabel("");
        setLabel(jl_null4);
        jta_balance = new JTextArea();
        jta_balance.setText("只能输入数字，其他数字无效");
        jta_balance.setFont(new Font("楷体", Font.PLAIN, 14));
        jta_balance.setForeground(Color.black);


        jta_balance.setLayout(new BorderLayout());

        jtf_balance.addKeyListener(new KeyAdapter() {

            @Override
            public void keyTyped(KeyEvent e) {
                char keyChar = e.getKeyChar();
                if (keyChar >= '0' && keyChar<= '9'){

                    return;
                }
                Toolkit.getDefaultToolkit().beep();

                e.consume();
            }
        });



        //限制输入长度
        jtf_balance.setDocument( new PlainDocument(){
            @Override
            public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {

                boolean psw= Pattern.matches("^[0-9]*$",jtf_balance.getText());
                String text = jtf_balance.getText();
                if (psw == true){
                    if (text.length() + str.length() > 10){
                        Toolkit.getDefaultToolkit().beep();
                        JOptionPane.showMessageDialog(toUpdateFrame.this,"余额超出10位数！");
                        return;

                    }
                }


                super.insertString(offs, str, a);
            }
        });

        jl_type = new JLabel("管理员:");
        setLabel(jl_type);

        jp_type = new JPanel();
        jp_type.setOpaque(true);
        jp_type.setBackground(Color.WHITE);

        buttonGroupSex = new ButtonGroup();

        jrb_type_man = new JRadioButton("用户");
        jrb_type_man.setSelected(true);
        jrb_type_man.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange()==ItemEvent.SELECTED){
                    i=0;
                }
            }
        });
        jrb_type_woman= new JRadioButton("管理员");

        jrb_type_woman.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {

                if(e.getStateChange()==ItemEvent.SELECTED){
                    i=1;

                }
            }
        });
        buttonGroupSex.add(jrb_type_man);
        buttonGroupSex.add(jrb_type_woman);

        jp_type.add(jrb_type_man);
        jp_type.add(jrb_type_woman);


        jl_phone = new JLabel("电话号码:");
        setLabel(jl_phone);

        jtf_phone = new JTextField();


        jl_null3 = new JLabel("");
        setLabel(jl_null3);
        jta_phone = new JTextArea();
        jtf_phone.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {

                jta_phone.setFont(new Font("微软雅黑",Font.PLAIN,14));
                jta_phone.setText("\n"+"请输入十一位数的电话号码");


            }
        });
        jtf_phone.addFocusListener(new FocusListener() {
            @Override
            public void focusLost(FocusEvent e) {
                boolean psw=Pattern.matches("^\\d{11}$",jtf_phone.getText());
                if(psw==false) {
                    if("".equals(jtf_phone.getText()) ) {
                        isVariable = false;
                        jta_phone.setEnabled(false);
                    }else {
                        jta_phone.setEnabled(true);
                        jta_phone.setFont(new Font("微软雅黑", Font.PLAIN, 14));
                        jta_phone.setText("\n" + "  手机号格式不对！");
                        isVariable = false;
                    }
                }else if(psw==true){
                    User user = new User();
                    UserDao userDao = new UserDao();
                    //调用方法查询数据库中是否与昵称文本域中内容相同
                    List<User> users = userDao.queryUsersByuPhone(jtf_phone.getText());
                    for (User user1 : users) {
                        user.setUphone(user1.getUphone());
                    }

                    jta_phone.setEnabled(true);
                    jtf_phone.getText();
                    jta_phone.setFont(new Font("微软雅黑",Font.PLAIN,14));
                    jta_phone.setText("\n"+"  手机号格式输入正确");
                    isVariable = true;
                }
            }
            @Override
            public void focusGained(FocusEvent e) {

                jta_phone.setText("\n"+"请输入十一位数的电话号码");
            }


        });

        jbt_submit = new JButton("提交");
        jbt_submit.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                User user = getUser();
                //调用方法查询数据库中是否与昵称文本域中内容相同

                //判断所有输入框中是否有空的
                if (!jtf_name.getText().equals("") && !jtf_password.getText().equals("")
                        && !jtf_balance.getText().equals("") && !jtf_phone.getText().equals("")) {
                    //判断用户名
                    if (variable == true) {
                        //判断密码正不正确
                        if ( passVariable == true){
                            //判断手机号正不正确
                            if (isVariable == true){
                                int i = 0;
                                if (mainFrame.getPnUser() == null) {
                                    //当前用户没有值，增加
                                    i = mainFrame.getUserDao().insertUser(user);
                                } else {
                                    i = mainFrame.getUserDao().updateUser2(user);
                                }
                                Toolkit.getDefaultToolkit().beep();
                                JOptionPane.showMessageDialog(toUpdateFrame, i > 0 ? "提交成功" : "提交失败");
                                //关闭自己
                                dispose();

                            }else if (jtf_phone.getText().equals(user.getUphone())) {
                                JOptionPane.showMessageDialog(toUpdateFrame, "提交失败！您输入的手机号格式不对或已被注册！"
                                        ,"错误", JOptionPane.ERROR_MESSAGE);
                            }


                        }else {
                            JOptionPane.showMessageDialog(toUpdateFrame, "提交失败！您输入的密码格式错误！"
                                    ,"错误", JOptionPane.ERROR_MESSAGE);
                        }


                    }else {
                        JOptionPane.showMessageDialog(toUpdateFrame, "提交失败！您输入的用户名格式不对或已被注册！"
                                ,"错误", JOptionPane.ERROR_MESSAGE);
                    }
                }else {
                    JOptionPane.showMessageDialog(toUpdateFrame, "提交失败！您输入的东西为空！"
                            ,"错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

    }

    public User getUser() {

        String name = jtf_name.getText();
        String password = jtf_password.getText();
        double balance = Double.parseDouble(jtf_balance.getText());
        int type = i;
        String phone = jtf_phone.getText();

        return new User(id, name, password, balance, type, phone);
    }

    public void setLabel(JLabel jl) {
        //水平居中
        jl.setHorizontalAlignment(SwingConstants.RIGHT);
        //垂直居中
        jl.setVerticalAlignment(SwingConstants.CENTER);
        //设置字体
        jl.setFont(new Font("微软雅黑", Font.PLAIN, 18));

    }

    public static void main(String[] args) {
        // new UpdateFrame(null, "增加数据", true);
    }

}
